package arr;

import java.util.Arrays;

/**
 * 手动实现一个动态数组
 * @author yifeng
 */
public class ArrayList {
    private int[] data;
    private int size = 10;
    private int position = 0;

    public ArrayList() {
        data = new int[size];
    }

    public ArrayList(int size) {
        this.size = size;
        data = new int[size];
    }

    public void add(int element) {
        if (position == size) {
            resize();
        }
        data[position++] = element;
    }

    public void addIndexOf(int index, int element) {
        if(position == size) {
            resize();
        }
        for(int i = position - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        data[index] = element;
        position++;
    }

    public void remove(int element) {
        for(int i = 0; i < position; i++) {
            if (data[i] == element) {
                removeIndexOf(i);
            }
        }
    }

    public void removeIndexOf(int index) {
        if (index == position - 1) {
            data[index] = 0;
        }
        for(int i = index; i < position; i++) {
            // 这里是不会越界原始数组 data 界的，因为 position 的位置永远都不会放元素
            data[i] = data[i+1];
        }
        position--;
    }

    public int get(int index) {
        if (index >= position) {
            throw new IllegalArgumentException("超出数组大小");
        }
        return data[index];
    }

    public void resize() {
        size = size + (size >>> 1);
        int[] newData = new int[size];
        for(int i = 0; i < position; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }

    public int size() {
        return position;
    }

    @Override
    public String toString() {
        return "ArrayList{" +
                "data=" + Arrays.toString(data) +
                ", size=" + size +
                ", position=" + position +
                '}';
    }

    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(5);
        list.add(6);
        list.add(7);
        list.addIndexOf(0, 3);
        list.addIndexOf(1, 4);
        System.out.println(list.get(4));
        System.out.println(list.get(0));
        System.out.println(list);
        list.remove(3);
        System.out.println(list);
        list.remove(6);
        System.out.println(list);
        for(int i = 7; i <= 17; i++) {
            list.add(i);
        }
        System.out.println(list);
        list.removeIndexOf(5);
        System.out.println(list);
    }
}
